package com.tyl.shiro.config;

import com.tyl.shiro.pojo.User;
import com.tyl.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.security.sasl.AuthorizeCallback;

// 自定义的UserRealm 需要继承 extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了----授权doGetAuthorizationInfo");
        //给user:add授权，让他可以访问
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         //info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();//拿到对象
        User principal = (User) subject.getPrincipal();//获取用户
        info.addStringPermission(principal.getPerms());//设置当前用户权限
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了----认证doGetAuthorizationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.queryUser(userToken.getUsername());
        if (user==null){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
